<?php


namespace app\common\job;


use app\common\model\QueueLog;
use think\facade\Log;
use think\queue\Job;

/**
 * Notes:基础job
 * DateTime 2021/7/2 14:02
 * @Author wind
 * Class BaseJob
 * @package app\manage\Job
 */
abstract class BaseJob
{
    abstract function doJob($data): array;

    /**
     * Notes:执行任务
     * DateTime 2021/7/2 14:02
     * @Author wind
     * @param Job $job
     * @param $data
     */
    public function fire(Job $job, $data)
    {
        $log = [
            'job'   => $job->getName(),
            'job_id'=> $job->getJobId(),
            'param' => json_encode($data),
            'drive' => $job->getConnection()
        ];
        try {
            if (class_exists($log['job'])){
                //执行业务处理
                $result = $this->doJob($data);
                $log['result_message'] = $result['msg'];
                if($result['code'] == 1){
                    $job->delete();//任务执行成功后删除
                    $log['result'] = 1;
                } else {
                    //检查任务重试次数
                    if($job->attempts() > 3){
                        $job->delete();
                    }
                }
            } else {
                $job->delete();
                $log['result_message'] = $log['job'] . '类不存在';
            }
            QueueLog::create($log);
        } catch (\Exception $e) {
            $msg = '任务处理失败：' . ' 行号：' . $e->getLine() . '文件：' . $e->getFile() . '错误信息：' . $e->getMessage();
            Log::channel('star')->error($msg);
        }

    }

    /**
     * Notes:成功数组通知
     * DateTime 2021/5/11 16:24
     * @Author wind
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return array
     */
    public function success($data = [], $msg = 'success', $code = 1): array
    {
        return [
            'code'    => $code,
            'msg' => $msg,
            'data'    => $data,
        ];
    }

    /**
     * Notes:失败数组通知
     * DateTime 2021/5/11 16:24
     * @Author wind
     * @param string $msg
     * @param int $code
     * @return array
     */
    public function error($msg = '', $code = 0): array
    {
        return [
            'code' => $code,
            'msg'  => $msg,
        ];
    }
}